#include "te_classgrade.h"
#include "ui_te_classgrade.h"

#include <QSet>
#include <QVariant>
#include <QList>
#include <QPair>
#include <algorithm>
#include <QTimer>

TE_ClassGrade::TE_ClassGrade(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::TE_ClassGrade)
{
    ui->setupUi(this);

    QStringList head = {"学号","姓名","成绩","绩点","排名"};
    TOOLS->setTableHead(ui->tableWidget,head);

    ui->tableWidget->setEditTriggers(QAbstractItemView::AllEditTriggers);


//    model = new QSqlQueryModel();
//    model->setQuery("SELECT * FROM studentGrades");

//    ui->tableWidget.setm
}

TE_ClassGrade::~TE_ClassGrade()
{
    delete ui;
}

void TE_ClassGrade::setDataToTable(const QList<DB_View_StudentGrades> &data)
{
    ui->tableWidget->setRowCount(data.count());

    QList<double> values;
    for(int r = 0;r<data.count() ; r++){
        auto&& cur = data[r];

        values <<  cur.GPA;
    }


    for(int r = 0;r<data.count() ; r++){
        auto&& cur = data[r];

        QString info = "%0,%1,%2,%3,%4";
        info = info.arg(cur.id)
                .arg(cur.name)
//                .arg(cur.courseID)
//                .arg(cur.coureName)
//                .arg(cur.credit)
                .arg(cur.grade)
                .arg(cur.GPA)
                .arg(cur.rankingInClass);

        QStringList curStrs = info.split(",");

        for(int c = 0 ; c< curStrs.count();c++){
            ui->tableWidget->setItem(r,c,new  QTableWidgetItem(curStrs[c]));
        }
    }

}

void TE_ClassGrade::setDataToTable(const QList<DB_View_StudentInfo> &data)
{
    ui->tableWidget->setRowCount(data.count());



    for(int r = 0;r<data.count() ; r++){
        auto&& cur = data[r];

        QString info = "%0,%1,%2,%3,%4";
        info = info.arg(cur.id)
                .arg(cur.name)
                .arg("")
                .arg("")
                .arg("");
//                .arg(cur.courseID)
//                .arg(cur.coureName)
//                .arg(cur.credit)
//                .arg("")
//                .arg("")

        QStringList curStrs = info.split(",");

        for(int c = 0 ; c< curStrs.count();c++){
            ui->tableWidget->setItem(r,c,new  QTableWidgetItem(curStrs[c]));
        }
    }
}



void TE_ClassGrade::on_comboBox_activated(int index)
{
    // 辅导员
    if(GDATA->userType == 1){
//        auto classId = ui->comboBox->currentData().toInt();
//        QString where = QString("classID = %1").arg(classId);

//        setCourseComboBox(where);
    }
    // 教师
    else if(GDATA->userType == 2){
        auto classId = ui->comboBox->currentData().toInt();

        QString where = QString("classID = %1 AND TAccount = %2").arg(classId).arg(GDATA->Account);

        setCourseComboBox(where);
    }
}

int TE_ClassGrade::getClassId()
{
    return ui->comboBox->currentData().toInt();
}

void TE_ClassGrade::setClassComboBox(QString where)
{
    auto data = DB->getAllClassInfo(where);
    auto combo = ui->comboBox;

    combo->clear();
    QSet<int> set;
    QSignalBlocker blocker(combo);

    for(auto && item:data){
        if(set.contains(item.classID)){
            continue;
        }

        combo->addItem(item.className,item.classID);
        set.insert(item.classID);
    }

    if(data.count() > 0){
        QTimer::singleShot(50,[=](){
            on_comboBox_activated(0);
        });
    }
}

void TE_ClassGrade::setCourseComboBox(QString where)
{
    auto data = DB->getAllClassInfo(where);
    auto combo = ui->comboBox_2;

    combo->clear();
    QSet<int> set;
    QSignalBlocker blocker(combo);

    for(auto && item:data){
        auto id = item.courseID;
        if(set.contains(id)){
            continue;
        }
        combo->addItem(item.courseName,id);
        set.insert(id);
    }

    if(data.count() > 0){
        QTimer::singleShot(50,[=](){
            on_comboBox_2_activated(0);
        });
    }
}

QList<int> TE_ClassGrade::generateReverseRankings(const QList<double> &doubleList) {

    QList<int>  intList;
    for (const auto &value : doubleList) {
        int rank = std::count_if(doubleList.begin(), doubleList.end(), [&](double x) { return x > value; });
        intList.append(rank + 1);
    }
    return intList;
}

void TE_ClassGrade::showEvent(QShowEvent *event)
{

    // 辅导员
    if(GDATA->userType == 1){



    }
    // 教师
    else if(GDATA->userType == 2){
        auto where = QString("TAccount = %1").arg(GDATA->Account);

        setClassComboBox(where);
    }
}


void TE_ClassGrade::on_comboBox_2_activated(int index)
{
    updateTable();
}

int TE_ClassGrade::getCourseId()
{
    return ui->comboBox_2->currentData().toInt();

}

void TE_ClassGrade::updateTable()
{
    auto classID = ui->comboBox->currentData().toInt();
    auto courseID = ui->comboBox_2->currentData().toInt();

    QString where =  QString("classID = %1 AND courseID = %2").arg(classID).arg(courseID);

    auto data = DB->getAllStudentGrades(where);

    QString whereClass = QString("classID = %1").arg(classID);
    auto studentList = DB->getAllStudentInfo(whereClass);

    if(data.count()  != studentList.count()){
        setDataToTable(studentList);
    }else{
        setDataToTable(data);
    }

}


void TE_ClassGrade::on_pushButton_clicked()
{
    on_pushButton_2_clicked();

}

void TE_ClassGrade::on_pushButton_2_clicked()
{
    auto res = CSV->tabelSaveFile(ui->tableWidget,TOOLS->openCSVSaveDialog());
    if(res){
        LOG("导出成功");
    }else{
        return ;
    }
}

void TE_ClassGrade::on_pushButton_3_clicked()
{
    auto res = CSV->tabelLoadFile(ui->tableWidget,TOOLS->openCSVOpenDialog());

    if(res){
        LOG("加载成功");
    }else{
        LOG("加载失败");
        return ;
    }
}


void TE_ClassGrade::on_pushButton_4_clicked()
{
    auto rowCoumt = ui->tableWidget->rowCount();
    auto c = getCourseId();

    auto table = ui->tableWidget;
    QList<QVariantList> inData;
    QList<double> values;
    for (int row =0;row < rowCoumt ; row++) {
        auto id = table->item(row,0)->text().toInt();
        auto g = table->item(row,2)->text().toDouble();
        values <<  g;

//        auto rq = table->item(row,2)->text().toDouble();
        inData.append({id,getCourseId(),g});

    }

    QList<int> rankings = generateReverseRankings(values);

    for(int r = 0;r<inData.count() ; r++){
        auto&& cur = inData[r];

        cur << rankings[r];

        inData[r] = cur;
    }

    QString tableName = "grades";
    QSqlQuery query;

    query.exec("begin;");


    for (auto && data:inData) {
        QString where = QString("%0 < student_id < %1 AND course_id = %2")
                .arg(getClassId()*100)
                .arg(getClassId()*100+99)
                .arg(getCourseId());
        DB->deleteTableInfo(tableName,where,&query);
    }


    DB->insertTableInfo(tableName,
                         inData,
                         &query);




    if (query.exec("commit;")){
        LOG("上传成功");
        updateTable();
    }else{
        LOG("失败");
        query.exec("rollback;");
    }
}

